﻿using System;

using System.ComponentModel;
using System.Data;
using System.Windows;
using WPFExcelReport.Helpers;
using ReflectionStudio.Core.Events;
using System.Windows.Data;
namespace WPFExcelReport
{
    public partial class TAB50COMBINE
    {
        public TAB50COMBINE()
        {
            if (DesignerProperties.GetIsInDesignMode(this))
                return;
            InitializeComponent();
        }
        public override void QueryCommand(object sender, RoutedEventArgs e)
        {
            base.QueryCommand(sender, e);
            IsVKPMode = false;
            ORDERNUM = KRS + LFD + "010";
        }
        bool IsVKPMode = false;
        public void QueryVKPCommand(object sender, RoutedEventArgs e)
        {

            base.QueryCommand(sender, e);
            IsVKPMode = true;
            dwData = TMV.VVKP.TBMain.NewRow();
            dwData["VKPMANDANT"] = app.Mandant;
            dwData["VKPAUFKRS"] = KRS;
            dwData["VKPAUFLFD"] = LFD;
            if (POS == "000" || POS == "")
            {

            }
            else
            {
                dwData["VKPAUFPOS"] = " AND ABAVKAUFPOS='" + POS + "'";
            }

            SResult = TMV.VVKP.QVKP30(dwData);
            MergeData(SResult, true);
            if (TBDetail.Rows.Count == 0)
            {
                TBDetail.Merge(TBMain);
                TBDetail.Clear();
            }

        }
        string CKRS = "", CLFD = "", CPOS = "", CART = "", CFARBE = "";
        double QTYBASE = 0;
        double QTYTOTAL = 0;
        DataRow dwBase = null;
        public override void LOADBYAUF()
        {
            if (MV == null)
                return;
            base.LOADBYAUF();
            PM["ORDERNUM"] = ORDERNUM;
            TMV.LOAD(PM);
            vwMaster.View.MoveCurrentToFirst();
            FINDSAME();
        }
        public void FINDSAME()
        {
            if (dwMaster == null)
                return;
            dwBase = TBMain.Clone().NewRow();
            dwBase.ItemArray = dwMaster.ItemArray;
            QTYTOTAL = 0;
            QTYBASE = Convert.ToDouble(dwAB["ABPSOLLMENGE5"].ToString());

            CKRS = dwMaster["ABPAUFKRS"].ToString();
            CLFD = dwMaster["ABPAUFLFD"].ToString();
            CPOS = dwMaster["ABPAUFPOS"].ToString();
            string rulekey = CKRS + CLFD + CPOS + dwMaster["ABPPOSTYP"].ToString();
            dwData = TMV.VPR.TBMain.NewRow();
            dwData["ORDERNUM"] = rulekey;
            SResult = TMV.VPR.QPRULES02(dwData);
            foreach (DataRow row in SResult.Tables[0].Rows)
            {
                dwBRule = SResult.Tables[0].Clone().Rows.Add();
                dwBRule.ItemArray = row.ItemArray;
                break;
            }
            CART = dwAB["ABPART"].ToString();
            CFARBE = dwAB["ABPFARBE"].ToString();
            dwData = TBMain.NewRow();
            dwData["ABPMANDANT"] = app.Mandant;
            dwData["ABPAUFKRS"] = " AND ABPAUFKRS='" + CKRS + "'";
            dwData["ABPAUFLFD"] = dwAB["ABPAUFLFD"];
            dwData["ABPART"] = dwAB["ABPART"];
            dwData["ABPFARBE"] = dwAB["ABPFARBE"];
            SResult = TMV.QABP251(dwData);
            MergeData(SResult, true, true);
            vwMaster.View.MoveCurrentToFirst();
        }
        private void btnRefresh_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                dwData = TBMain.NewRow();
                dwData["ABPAUFKRS"] = " AND ABAAUFKRS='" + CKRS + "'";
                dwData["ABPAUFLFD"] = CLFD;
                dwData["ABPART"] = CART;
                dwData["ABPFARBE"] = CFARBE;
                SResult = TMV.QABP251(dwData);
                btnCombine_Click(null, null);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        //MainViewModel MainViewModel; 
        private void btnCombine_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (dwAB == null)
                {
                    MessageBox.Show("请先选择要合并的生产单");
                    return;
                }
                if (CLFD == "")
                {
                    if (IsVKPMode)
                    {
                        CKRS = dwAB["ABPAUFKRS"].ToString();
                        CLFD = dwAB["ABPAUFLFD"].ToString();
                        CPOS = dwAB["ABPAUFPOS"].ToString();
                        string rulekey = CKRS + CLFD + CPOS + dwMaster["ABPPOSTYP"].ToString();
                        dwData = TMV.VPR.TBMain.NewRow();
                        dwData["ORDERNUM"] = rulekey;
                        SResult = TMV.VPR.QPRULES02(dwData);
                        foreach (DataRow row in SResult.Tables[0].Rows)
                        {
                            dwBRule = SResult.Tables[0].Clone().Rows.Add();
                            dwBRule.ItemArray = row.ItemArray;
                            break;
                        }
                        dwBase = TBMain.Clone().NewRow();
                        dwBase.ItemArray = dwAB.ItemArray;
                    }
                    else
                    {
                        MessageBox.Show("请先选择要合并的生产单");
                        return;
                    }

                }
                if (TBDetail == null)
                {
                    TBDetail = MV.SetData.Tables["ABPOS"];
                    TBDetail.Merge(TBMain.Clone());
                }
                else
                {
                    if (TBDetail.Rows.Count == 0)
                    {
                        TBDetail = MV.SetData.Tables["ABPOS"];
                        TBDetail.Merge(TBMain.Clone());
                    }
                }
                string _KRS = dwAB["ABPAUFKRS"].ToString();
                string _LFD = dwAB["ABPAUFLFD"].ToString();
                string _POS = dwAB["ABPAUFPOS"].ToString();
                vwMaster.View.MoveCurrentTo(-1);
                filter = "ABPAUFKRS='" + _KRS + "' AND ABPAUFLFD='" + _LFD + "' AND ABPAUFPOS='" + _POS + "'";
                rows = TBMain.Select(filter);
                foreach (DataRow row in rows)
                {
                    dwData = TBDetail.Rows.Add();
                    dwData.ItemArray = row.ItemArray;
                    row.Delete();
                }
                TBMain.AcceptChanges();
                if (vwDetail != null)
                    vwDetail.Source = TBDetail;
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        public DataRow dwBRule = null;
        private void btnCombineConvert_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (dwBRule == null)
                {
                    MessageBox.Show("请选择复板单?");
                    return;
                }
                string msg = "";
                int TTS = 1;
                if (TBDetail == null)
                    return;
                //建立需要合并的生产单列表              
                //放大母生产单数量
                //删除其他生产单
                //找到这些生产单对应的AB52，修改生产单号码和行号，进行行号更新，保存
                //找到ICC_ABAX,修改行号，进行行号更新
                TTS = TBDetail.Rows.Count;
                if (TTS < 2)
                {
                    MessageBox.Show("再来一个!");
                    return;
                }

                EventDispatcher.Instance.RaiseStatus("开始合投", StatusEventType.RunningProgress);
                #region======== //找到这些生产单对应的AB52，修改生产单号码和行号，进行行号更新，保存
                DataSet STemp = new DataSet();
                double VKPTOTAL = 0;
                QTYTOTAL = 0;
                double BaseQTY = Convert.ToDouble(dwBase["ABPSOLLMENGE5"].ToString());
                foreach (DataRow row in TBDetail.Rows)
                {
                    QTYTOTAL += Convert.ToDouble(row["ABPSOLLMENGE5"].ToString());
                    VKPTOTAL += Convert.ToDouble(row["ABPSOLLMENGE7"].ToString());
                    PM["ORDERNUM"] = row["ABPAUFKRS"].ToString() + row["ABPAUFLFD"].ToString() + row["ABPAUFPOS"].ToString();
                    SResult = TMV.VMU.ABLOAD(PM);
                    STemp.Merge(SResult);
                    SResult = TMV.VGD.LOAD(PM);
                    STemp.Merge(SResult);
                }
                #region======== 更新粗砂编码=========
                PM["ABPART"] = dwBase["ABPART"].ToString();
                PM["ABAVAR"] = dwBase["ABPVAR"].ToString();
                PM["ABAFARBE"] = dwBase["ABPFARBE"].ToString();
                EventDispatcher.Instance.RaiseStatus("更新粗砂编码", StatusEventType.RunningProgress);
                foreach (DataRow row in TBDetail.Rows)
                {
                    string KKRS = row["ABPAUFKRS"].ToString();
                    string KLFD = row["ABPAUFLFD"].ToString();
                    string KPOS = row["ABPAUFPOS"].ToString();                  
                    //row["VKPEXART"] = Helper.ConvertGB2312To8859P1("0.合投开始").PadRight(20);
                    if (IsVKPMode)
                    {
                        row["VKPEXAUFKRS"] = CKRS;
                        row["VKPEXAUFLFD"] = CLFD;
                        row["VKPEXAUFPOS"] = CPOS;
                        TMV.VVKP.UVKP11B(row);
                    }
                    if (KKRS + KLFD + KPOS == CKRS + CLFD + CPOS)
                        continue;
                    PM["dwABP"] = row;
                    PM["ABPAUFKRS"] = KKRS;
                    PM["ABPAUFLFD"] = KLFD;
                    PM["ABPAUFPOS"] = KPOS;
                    CHGAB50ART(PM);

                }
                #endregion
                #region============== 放大母生产单数量===========
                dwBase["ABPSOLLMENGE5"] = QTYTOTAL;
                dwBase["ABPSOLLMENGE7"] = VKPTOTAL;

                double RATIO = Math.Round(QTYTOTAL / VKPTOTAL, 5);
                msg = "合并后的数量是:" + QTYTOTAL * 0.01 + ",订单量" + VKPTOTAL * 0.01 + ",投料比:" + Helper.RoundX(RATIO, 1) + "%";
                if (MessageBox.Show(msg + "!", "请确认", MessageBoxButton.YesNoCancel) != MessageBoxResult.Yes)
                {
                 
                    return;
                  
                }
                EventDispatcher.Instance.RaiseStatus(msg, StatusEventType.RunningProgress);
                msg = "更新生产单:" + dwBase["ABPAUFKRS"].ToString()
                    + dwBase["ABPAUFLFD"].ToString()
                    + dwBase["ABPAUFLFD"].ToString()
                    + ",ABPSOLLMENGE5:"
                    + dwBase["ABPSOLLMENGE5"].ToString()
                    + ",ABPSOLLMENGE7:"
                    + dwBase["ABPSOLLMENGE7"].ToString();
                EventDispatcher.Instance.RaiseStatus(msg + "开始", StatusEventType.RunningProgress);
                TMV.UABP07(dwBase);
                TMV.VABF.UABF04(dwBase);
                EventDispatcher.Instance.RaiseStatus(msg + "完成", StatusEventType.RunningProgress);
                filter = "GAAUFKRS='" + CKRS + "' AND GAAUFLFD='" + CLFD + "' AND GAAUFPOS='" + CPOS + "'";
                rows = STemp.Tables["GAAUF"].Select(filter);
                double QTYMAT = 0;
                foreach (DataRow row in rows)
                {
                    row["GAKG1"] = Helper.RoundX(Convert.ToDouble(row["GAKG1"].ToString()) * QTYTOTAL / BaseQTY, 1);
                    row["GAKG2"] = Helper.RoundX(Convert.ToDouble(row["GAKG2"].ToString()) * QTYTOTAL / BaseQTY, 1);

                    if (row["GASA"].ToString() == "713")
                    {
                        QTYMAT += Convert.ToDouble(row["GAKG1"].ToString()) * 0.01;
                    }
                    TMV.VGD.UGD07(row);
                }
                dwBRule["VKPQTY"] = VKPTOTAL * 0.01;
                dwBRule["QTYEND"] = QTYTOTAL * 0.01;
                dwBRule["QTYMAT"] = QTYMAT;
                TMV.VPR.UpdateICC_PRULES(dwBRule, 1);
                foreach (DataRow row in STemp.Tables["GAAUF"].Rows)
                {
                    TMV.VGL.RVZUTEI(row);
                }
                TMV.UABP06(dwBase);
                msg = "更新GAAUF:" + dwBase["ABPAUFKRS"].ToString() + dwBase["ABPAUFLFD"].ToString() + dwBase["ABPAUFLFD"].ToString();
                EventDispatcher.Instance.RaiseStatus(msg, StatusEventType.RunningProgress);
                #endregion
                filter = "ABAAUFKRS='" + CKRS + "' AND ABAAUFLFD='" + CLFD + "' AND ABAAUFPOS='" + CPOS + "' AND ABAAPOS='0001'";
                rows = STemp.Tables["ABAUFM"].Select(filter);
                DataRow dwMUBase = null;
                foreach (DataRow row in rows)
                {
                    dwMUBase = row;
                }
                if (dwMUBase == null)
                    return;
                EventDispatcher.Instance.RaiseStatus("处理留位关系", StatusEventType.RunningProgress);
                int ABALEAPOS = Convert.ToInt16(dwMUBase["ABALEAPOS"].ToString());
                foreach (DataRow dwMU in STemp.Tables["ABAUFM"].Rows)
                {
                    string VKAUFKRS = dwMU["ABAVKAUFKRS"].ToString();
                    string VKAUFLFD = dwMU["ABAVKAUFLFD"].ToString();
                    string VKAUFPOS = dwMU["ABAVKAUFPOS"].ToString();
                    string AUFKRS = dwMU["ABAAUFKRS"].ToString();
                    string AUFLFD = dwMU["ABAAUFLFD"].ToString();
                    string AUFPOS = dwMU["ABAAUFPOS"].ToString();
                    string ABAAPOS = dwMU["ABAAPOS"].ToString();
                    if (VKAUFLFD.ToString() == "000000")
                        continue;
                    dwData = TMV.VABK.TBMain.NewRow();
                    dwData["ABKMANDANT"] = app.Mandant;
                    dwData["ABKAUFKRS"] = VKAUFKRS;
                    dwData["ABKAUFLFD"] = VKAUFLFD;
                    dwData["ABKARTSB"] = Helper.ConvertGB2312To8859P1("合投").PadRight(8);
                    TMV.VABK.UABK04(dwData);
                    if (AUFKRS + AUFLFD + AUFPOS == CKRS + CLFD + CPOS)
                        continue;
                    TMV.VMU.DMU01(dwMU);
                    ABALEAPOS++;
                    dwMU["ABAAUFKRS"] = CKRS;
                    dwMU["ABAAUFLFD"] = CLFD;
                    dwMU["ABAAUFPOS"] = CPOS;
                    dwMU["ABAPRAUFKRS"] = AUFKRS;
                    dwMU["ABAPRAUFLFD"] = AUFLFD;
                    dwMU["ABAPRAUFPOS"] = AUFPOS;
                    dwMU["ABAAPOS"] = Helpers.Helper.Right("0000" + ABALEAPOS.ToString(), 4);
                    dwMU["ABARESZEIT"] = TTS;
                    TMV.VMU.InsertABAUFM(dwMU, app.company);

                }

                dwMUBase["ABASGESGEW"] = QTYTOTAL * 10;
                dwMUBase["ABALEAPOS"] = ABALEAPOS;
                TMV.VMU.UMU07(dwMUBase);

                #endregion

                #region======== //删除其他生产单
                EventDispatcher.Instance.RaiseStatus("删除其他生产单", StatusEventType.RunningProgress);
                foreach (DataRow row in TBDetail.Rows)
                {
                    string KKRS = row["ABPAUFKRS"].ToString();
                    string KLFD = row["ABPAUFLFD"].ToString();
                    string KPOS = row["ABPAUFPOS"].ToString();
                    if (KKRS + KLFD + KPOS == CKRS + CLFD + CPOS)
                        continue;
                    PM["ORDERNUM"] = KKRS + KLFD + KPOS + row["ABPPOSTYP"].ToString();
                    PM["ABPSPGRD"] = "  ";
                    TMV.ENDABP(PM);
                    TMV.VABF.ENDABF(PM);
                    //INTEXBL.DELTEABPOS(app.Mandant, KKRS, KLFD, KPOS);
                }
                #endregion
                CLFD = "";
                TBDetail.Clear();
                //ORDERNUM = dwAB["ABPAUFKRS"].ToString() + dwAB["ABPAUFLFD"].ToString() + dwAB["ABPAUFPOS"].ToString() + dwAB["ABPPOSTYP"].ToString();
                string order = dwBase["ABPAUFKRS"].ToString() + dwBase["ABPAUFLFD"].ToString() + dwBase["ABPAUFPOS"].ToString() + dwBase["ABPPOSTYP"].ToString();
                PM["ORDERNUM"] = order;
                PM["RUNID"] = RUNID;
                TMV.LOADABP(PM);
            }
            catch (Exception ex)
            {
                MessageBox.Show("合投有异常发生" + ex.Message);
                Tracer.Error(ex.StackTrace, ex);
                EventDispatcher.Instance.RaiseStatus("异常", StatusEventType.StopProgress);
            }
            finally
            {
                EventDispatcher.Instance.RaiseStatus("合投完成", StatusEventType.StopProgress);
            }
      
        }
        private void btnRemoveFromCombine_Click(object sender, RoutedEventArgs e)
        {
            if (TBDetail == null)
                return;
            TBMain.Merge(TBDetail);
            TBDetail.Clear();
            TBMain.AcceptChanges();
        }
    }
}
